package com.cmlite;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import org.json.JSONException;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;

import com.cmlite.base.BaseActivity;
import com.cmlite.base.BaseInit;
import com.cmlite.component.ClearableEditText;
import com.cmlite.connect.AsyncTask_Api;
import com.cmlite.connect.AsyncTask_ApiListener;
import com.cmlite.connect.CallApi;
import com.cmlite.connect.ScreenStopper;
import com.cmlite.model.OutResult;
import com.cmlite.util.ConnectionException;
import com.cmlite.util.EmptyDataException;
import com.cmlite.util.TokenUnableException;
import com.cmlite.util.Util;

public class A001Register extends BaseActivity implements BaseInit,
		OnClickListener, AsyncTask_ApiListener {
	private static final String TAG  = A001Register.class.getName();

	private TextView btn_back, tv_title, btn_done;
	private ClearableEditText et_organization, et_firstname, et_lastname,
			et_email, et_comfirmemail, et_password,et_address, et_plz, et_stadt;
	private EditText et_birthday;
	private Button btn_birthday;

	static final int DATE_DIALOG_ID = 0;
	static final int TYPE_REGISTER = 3;
	private long birthday  = new Date().getTime();
	
	
	private String strOrganization,
	               strFirstName,
	               strLastName,
	               strEmail,
	               strPassword,
	               strBirthday,
	               strAddress,
	               strPlz,
	               strStadt;

	private HashMap<String, String> hashMap;

	@Override
	public void onIOnCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		initView();
	}

	@Override
	public void onIRestart() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onIStart() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onIResume() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onIDestroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onIActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onIBackPressed() {
		// TODO Auto-generated method stub

	}

	@Override
	public void initView() {
		// TODO Auto-generated method stub
		setContentView(R.layout.a001register);

		this.tv_title = (TextView) findViewById(R.id.header_tv_title);
		this.btn_back = (TextView) findViewById(R.id.header_tv_back);
		this.btn_done = (TextView) findViewById(R.id.header_tv_next);

		this.btn_back.setVisibility(View.VISIBLE);
		this.btn_done.setVisibility(View.VISIBLE);

		this.et_organization = (ClearableEditText) findViewById(R.id.a001_et_organization);
		this.et_firstname = (ClearableEditText) findViewById(R.id.a001_et_firstname);
		this.et_lastname = (ClearableEditText) findViewById(R.id.a001_et_lastname);
		this.et_email = (ClearableEditText) findViewById(R.id.a001_et_email);
		this.et_comfirmemail = (ClearableEditText) findViewById(R.id.a001_et_confirmemail);
		this.et_password = (ClearableEditText) findViewById(R.id.a001_et_password);
		this.et_birthday = (EditText) findViewById(R.id.a001_et_birthday);
		this.et_plz = (ClearableEditText) findViewById(R.id.a001_et_plz);
		this.et_stadt = (ClearableEditText) findViewById(R.id.a001_et_stadt);
		this.et_address  = (ClearableEditText) findViewById(R.id.a001_et_address);
		this.btn_birthday = (Button) findViewById(R.id.a001_btn_birthday);

		this.btn_back.setOnClickListener(this);
		this.btn_done.setOnClickListener(this);
		this.btn_birthday.setOnClickListener(this);

		initData();
	}

	@Override
	public void initData() {
		// TODO Auto-generated method stub
//		this.tv_title.setText(mRes.getString(R.string.title_register));
		this.btn_done.setBackgroundResource(R.drawable.finished_work_normal);
		birthday  = new Date().getTime();

        // display the current date (this method is below)
        updateDisplay();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.header_tv_back:
			Intent i = new Intent(this, A1002Login.class);
			setResult(1, i);
			finish();
			break;
		case R.id.header_tv_next:
			isCheckRegister();
			break;
		case R.id.a001_btn_birthday:
			showDialog(DATE_DIALOG_ID);
			break;
		default:
			break;
		}
	}

	// updates the date in the TextView
    @SuppressLint("SimpleDateFormat")
	private void updateDisplay() {
    	Date t  = new Date(birthday);
		String newstring = new SimpleDateFormat("dd.MM.yyyy").format(t);
		et_birthday.setText(newstring);  
    }
	// the callback received when the user "sets" the date in the dialog
	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

		 public void onDateSet(DatePicker view, int year,
                 int monthOfYear, int dayOfMonth) {
                        Calendar  calendar  = Calendar.getInstance();
                        calendar.set(year, monthOfYear, dayOfMonth);
                        birthday  = calendar.getTimeInMillis();
                        Date t  = new Date(birthday);
                       String newstring = new SimpleDateFormat("dd.MM.yyyy").format(t);
                       et_birthday.setText(newstring);
}
	};

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			Date t  = new Date(birthday);
			Calendar  calendar  = Calendar.getInstance();
			calendar.setTime(t);
			return new DatePickerDialog(this, mDateSetListener, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH));
		}
		return null;
	}

	private void isCheckRegister() {
		try {
			String msg = null;
			String organization, firstname, lastname, email, comfirnemail, password, birthday, plz, stadt;

			organization   = et_organization.getText().toString().trim();
			firstname      = et_firstname.getText().toString().trim();
			lastname       = et_lastname.getText().toString().trim();
			email          = et_email.getText().toString().trim();
			comfirnemail   = et_comfirmemail.getText().toString().trim();
			password       = et_password.getText().toString().trim();
			birthday       = et_birthday.getText().toString().trim();
			plz            = et_plz.getText().toString().trim();
			stadt          = et_stadt.getText().toString().trim();
			String format  = String.format("organization : %s\n" +
											"firstname   : %s\n" +
											"lastname    : %s\n" +
											"email       :%s\n" +
											"comfirnemail  :%s\n" +
											"password     :%s\n" +
											"birthday     :%s\n" +
											"plz     : %s\n" +
											"stadt     : %s\n",organization,firstname,
											                      lastname,email,comfirnemail,
											                      password,birthday,plz,stadt);
			                              
			Log.d(TAG,format);

			if (Util.isEmpty(organization))
				msg = mRes.getString(R.string.error_organization);
			else if (Util.isEmpty(firstname))
				msg = mRes.getString(R.string.error_firstname);
			else if (Util.isEmpty(lastname))
				msg = mRes.getString(R.string.error_lastname);
			else if (Util.isEmpty(email))
				msg = mRes.getString(R.string.error_email);
			else if (Util.isEmpty(comfirnemail))
				msg = mRes.getString(R.string.error_confirmemail);
			else if (Util.validateEmailAddress(email) == false)
				msg = mRes.getString(R.string.msg_error_incorret_gmail);
			else if (Util.validateEmailAddress(comfirnemail) == false)
				msg = mRes.getString(R.string.msg_error_incorret_gmail);
			else if (!Util.checkEqualString(email, comfirnemail))
				msg = mRes.getString(R.string.msg_error_gmail_match);
			else if (Util.isEmpty(password))
				msg = mRes.getString(R.string.error_password);
			else if (Util.isEmpty(birthday))
				msg = mRes.getString(R.string.error_birthday);
			else if (Util.isEmpty(plz))
				msg = mRes.getString(R.string.error_plz);
			else if (Util.isEmpty(stadt))
				msg = mRes.getString(R.string.error_stadt);

			if (!Util.isEmpty(msg)) {
				Util.showDialog(mContext, R.string.title_register, msg,
						R.drawable.exclamation);
				return;
			} else {
				hashMap = new HashMap<String, String>();
                strOrganization = et_organization.getText().toString();
                strEmail        = et_email.getText().toString();
                strFirstName    = et_firstname.getText().toString();
                strLastName     = et_lastname.getText().toString();
                strPassword     = et_password.getText().toString();
                strPlz          = et_plz.getText().toString();
                strStadt        = et_stadt.getText().toString();
                strBirthday     = et_birthday.getText().toString();
                strAddress      = et_address.getText().toString();
				getRegister();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	@Override
	public Object callApi(int serachType, Object apidata) {
		// TODO Auto-generated method stub
		if (serachType == TYPE_REGISTER) {
           try {
			return CallApi.postRegister(this,strOrganization, strFirstName, 
					                  strLastName, strEmail, strPassword, strBirthday, strPlz, strStadt,strAddress);
		  } catch (EmptyDataException e) {
			e.printStackTrace();
		  } catch (ConnectionException e) {
			e.printStackTrace();
		  } catch (JSONException e) {
			e.printStackTrace();
		  } catch (TokenUnableException e) {
			e.printStackTrace();
		  }
		}
		return null;
	}

	@Override
	public void finishApi(int serachType, Object apiresult) {
		if (serachType == TYPE_REGISTER) {
			if(apiresult != null){
				OutResult  out  = (OutResult) apiresult;
				if(out.getStatus()){
					this.finish();
				}else{
					Util.showDialog(this, R.string.error, out.getMessage(),R.drawable.exclamation);
				}
			}
			
		}
	}

	@Override
	public void tokenExpride() {
		

	}

	private void getRegister() {
		if (Util.getNetworkStatus(this)) {
			AsyncTask_Api apiTask = new AsyncTask_Api(this, this,
					TYPE_REGISTER, 0, ScreenStopper.STYLE_PROGRESS_PROCESS);
			apiTask.execute();
		} else {
			Util.showDialog(this, R.string.warning,
					R.string.network_not_available, R.drawable.exclamation);
		}
	}
}
